# web/dispatch.py
#
#

__copyright__ = 'this file is in the public domain'

from plugs.webserver import httpd
from ommbot.world import get_fleet, get_plugs
from ommbot.ircevent import Ircevent
from cgi import escape
from urllib import unquote_plus
import Queue
import time

def handle_dispatch(event):
    input = unquote_plus(event.path)
    fleet = get_fleet()
    if not fleet:
        return []
    bot = fleet.byname('main')
    if not bot:
        return []
    ievent = Ircevent()
    try:
        what = input.split('?', 1)[1]
    except IndexError:
        return ["dispatch what ?",]
    if what.startswith("command="):
        what = what[8:]
    dowait = 0
    if ' wait' in what:
        what = what.rsplit(' wait')[0]
        dowait = 1
    ievent.txt = what
    ievent.nick = 'web'
    ievent.userhost = 'web@web'
    ievent.channel = 'web'
    q = Queue.Queue()
    ievent.queues.append(q)
    ievent.speed = 10
    ievent.bot = bot
    result = []
    if get_plugs().trydispatch(bot, ievent):
        while 1:
            res = q.get()
            if not res:
                break
            result.append(res)
    if not result:
        return ["can't dispatch %s" % what, ]
    return result

if httpd:
    httpd.addhandler('dispatch', handle_dispatch)
